const puppeteer = require('puppeteer')
const chalk = require('chalk')
const CosmeticsDetail = require('../controllers/base/cosmeticsDetail')
const log = console.log

module.exports = function(where) {
  start(where)
}

function formatProgress (current, total) { 
  let percent = (current / total) * 100
  let done = ~~(current / total * 40)
  let left = 40 - done
  let str = `progress: [${''.padStart(done, '=')}${''.padStart(left, '-')}]  ${percent}%`
  return str
}

async function start (where) {
  const browser = await puppeteer.launch({
    handless: false,
    devtools: true
  })
  log(chalk.green('server start...'))
  try {
    const page = await browser.newPage()
    // page.on('console', msg => {
    //   if (typeof msg === 'object') {
    //     console.dir(msg)
    //   } else {
    //     log(chalk.blue(msg))
    //   }
    // })

    const list = await CosmeticsDetail.getCosmeticsDetail(where)
    
    for(let i = 0; i <= list.length - 1; i++) {

      // console.clear()
      // log(chalk.yellow(formatProgress(i, list.length - 1)))

      if (list[i].classify) continue

      log(chalk.yellow('loading:' + list[i].link))
      await page.goto(list[i].link + '#comment', {
        timeout: 0
      })

      // await page.evaluate(() => {
      //   for (var y = 0; y <= 2000; y += 200) {
      //     window.scrollTo(0,y)
      //     }
      // })
      // await page.waitFor(500)
      // console.log(await handleData())
      try {
        let data = await handleData()
        await CosmeticsDetail.updateClassify({
          detail_id: list[i].detail_id
        }, JSON.stringify(data.classify), data.con)
      } catch (err) {
        console.log(err)
        // await browser.close()
        continue
      }
      await page.waitFor(300)

      async function handleData() {
        let data = await page.evaluate(() => {
          window.scrollTo(0, 0)
          const items = document.querySelector('.parameter2').getElementsByTagName('li')
          let len = 4
          if(items.length - 1 < 4) {
            len = items.length - 1
          }
          let parameters = {
            classify: []
          }
          for (let i = 0; i <= len; i++) {
            let _para = items[i].innerText.split('：')
            // if (!(_para[0] === '商品毛重' || _para[0] === '店铺' || _para[0] === '商品编号' || _para[0] === '货号' || _para[0] === '国产/进口' || _para[0] === '适用场景' || _para[0] === '商品名称')) {
              parameters.classify.push({ key: _para[0], value: _para[1]})
            // }
          }
          parameters.con = document.querySelector('.percent-con') ? document.querySelector('.percent-con').innerText : '暂无评分'
          return parameters
        })
        console.log(data)
        return data
      }
    }

  } catch (err) {
    console.log(err)
    log(chalk.red('error'))
    // await browser.close()
  } finally {
    process.exit(0)
  }
}
